package com.gexin.service.memberAcitivty;

import com.gexin.common.model.ApiResponse;
import com.gexin.common.utils.BigDecimalUtils;
import com.gexin.common.utils.MD5;
import com.gexin.common.utils.UUIDUtils;
import com.gexin.controller.commom.WeixinTransfer.model.WeixinTransferResult;
import com.gexin.controller.weixin.subscribe.CompanyToPerson;
import com.gexin.model.activity.*;
import com.gexin.model.enums.MemberInfoEnum;
import com.jfinal.aop.Before;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.gexin.model.activity.Company;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

public class CoinService {

    private MemberInfoService memberInfoService = new MemberInfoService();


    /**
     * 校验验证码
     *
     * @param verifyCode
     */
    public void verifyCode(String verifyCode) {

    }

    /**
     * 校验支付密码
     *
     * @param userId
     * @param password
     * @return
     */
    public ApiResponse getPayPassword(String userId, String password) {
        if (password == null) {
            return new ApiResponse(true, "请输入支付密码", 0);
        }
        PayInfo payInfo = PayInfo.dao.findByUserId(userId);
        if (payInfo != null && payInfo.getPayPassword() != null) {
            String payPassword = payInfo.getPayPassword();
            if (MD5.MD5EncodePass(password).equals(payPassword)) {
                return new ApiResponse(true, "校验成功", 200);
            }
        }
        return new ApiResponse(true, "暂为设置支付密码,请先设置支付密码", 0);
    }


    /**
     * 设置支付密码
     *
     * @param userId
     * @param password
     * @return
     */
    public ApiResponse getPayPassword(String userId, String password, String phone) {
        if (password == null) {
            return new ApiResponse(true, "请输入支付密码", 0);
        }
        PayInfo payInfo = PayInfo.dao.findByUserId(userId);
        if (payInfo == null) {
            String s = MD5.MD5EncodePass(password);
            payInfo = new PayInfo();
            payInfo.setId(UUIDUtils.getUUIDInOrderId() + "");
            payInfo.setPhone(phone);
            payInfo.setPayPassword(s);
            long date = new Date().getTime();
            payInfo.setCreateTime(date);
            payInfo.setUpdateTime(date);
            return new ApiResponse(true, "校验成功", 200);
        }
        return new ApiResponse(true, "暂为设置支付密码,请先设置支付密码", 0);
    }

    /**
     * 金币转账
     *
     * @param authUserId
     * @param presentId
     * @param
     */
    @Before(Tx.class)
    public ApiResponse presentCoin(String authUserId, String presentId, BigDecimal coin) {
        Map map = new HashMap();
        map.put("data", 0);
        ApiResponse apiResponse = memberInfoService.checkAuthtication(authUserId, presentId, coin, BigDecimal.ZERO, 1);
        if (apiResponse.isState() == false) {
            return apiResponse;
        }
        MemberBillSpeedIntegral memberBillSpeedIntegral = MemberBillSpeedIntegral.dao.getMemberBillSpeedIntegralByUserId(authUserId);
        MemberBillSpeedIntegral presendMemberBillSpeedIntegral = MemberBillSpeedIntegral.dao.getMemberBillSpeedIntegralByUserId(presentId);
        if (memberBillSpeedIntegral == null || memberBillSpeedIntegral.getCoin() == null) {
            return new ApiResponse(false, "可以转账为0", map);
        }
        BigDecimal coinMine = memberBillSpeedIntegral.getCoin();
        if (BigDecimalUtils.lessThan(coinMine, coin)) {
            return new ApiResponse(false, "转账金额超过本人佣金总额", map);
        }

//      转账人:剩下的金币以及日志
        coinMine = coinMine.subtract(coin);
        memberBillSpeedIntegral.setCoin(coinMine);
        memberBillSpeedIntegral.setUpdateTime(new Date().getTime());
        memberBillSpeedIntegral.update();
        MemberCoinLog memberCoinLog = new MemberCoinLog();
        memberCoinLog.setCommonUserIdAndCoinAndCoinIncrementAndIncomeOrAndTypeAndDesc(
                authUserId, presentId, null, 2, coinMine, coin, 0, "金币转账");
        memberCoinLog.save();

//      被转账人:剩下的金币
        if (presendMemberBillSpeedIntegral == null) {
//          多余,因为转账的时候只有粉客才能接受赠送
            presendMemberBillSpeedIntegral = new MemberBillSpeedIntegral();
            presendMemberBillSpeedIntegral.setUserIdAndSpeedIntegralAndCoinAndBillCouponAndForecastAndRemainAndReverseAndDailyIncrement
                    (presentId, BigDecimal.ZERO, coin, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO,
                            BigDecimal.ZERO, BigDecimal.ZERO);
            presendMemberBillSpeedIntegral.save();
        } else {
            BigDecimal presentCoin = presendMemberBillSpeedIntegral.getCoin() == null ?
                    BigDecimal.ZERO : presendMemberBillSpeedIntegral.getCoin();
            presentCoin = presentCoin.add(coin);
            presendMemberBillSpeedIntegral.setCoin(presentCoin);
            presendMemberBillSpeedIntegral.setUpdateTime(new Date().getTime());
            presendMemberBillSpeedIntegral.update();
        }
        MemberCoinLog presentMemberConLog = new MemberCoinLog();
        presentMemberConLog.setCommonUserIdAndCoinAndCoinIncrementAndIncomeOrAndTypeAndDesc(
                presentId, null, authUserId, 2, presendMemberBillSpeedIntegral.getCoin(),
                coin, 1, "金币转账");
        presentMemberConLog.save();

        return new ApiResponse(true, "转账成功", map);
    }


    /**
     * 兑换最大值
     *
     * @param
     * @return
     */
    @Before(Tx.class)
    public ApiResponse coinExchangeMoneyConvernet(String userId) {
        MemberInfo memberInfo = MemberInfo.dao.getMemberInfoByUserId(userId);
        int level = 0;
        Map map = new HashMap();
        map.put("balance", 0);
        if (memberInfo == null) {
            return new ApiResponse(false, "游客不能兑换,请确定无误后重试", map);
        }
        level = memberInfo.getLevel() == null ? 0 : memberInfo.getLevel();
        MemberLevel memberLevel = MemberLevel.dao.getMemberLevel(level);
        if (memberLevel == null || memberLevel.getLevel() == MemberInfoEnum.FIRST_LEVEL.getCode()) {
            return new ApiResponse(false, "游客不能兑换,请确定无误后重试", map);
        }
//      总积分
        BigDecimal coin = new BigDecimal("0");
        MemberBillSpeedIntegral memberBillSpeedIntegral = MemberBillSpeedIntegral.dao.getMemberBillSpeedIntegralByUserId(userId);
        if (memberBillSpeedIntegral != null) {
            coin = memberBillSpeedIntegral.getCoin() == null ? BigDecimal.ZERO : memberBillSpeedIntegral.getCoin();
        }
//      手续费
        double coinExchangeBalancePercent = MemberLevel.coinExchangeBalancePercent(memberLevel);
        BigDecimal commission = coin.multiply(BigDecimal.valueOf(coinExchangeBalancePercent));
//      提货券兑换比例
        BigDecimal balance = coin.subtract(commission);
        map.put("commission", commission);
        map.put("balance", balance);
        map.put("coinExchangeBalancePercent", coinExchangeBalancePercent);
        return new ApiResponse(true, "可以提现", map);
    }

    /**
     * 金币兑换成现金
     *
     * @param authUser
     * @return
     */
    @Before(Tx.class)
    public ApiResponse coinExchangeMoney(String authUser, String money, String openid) {

        ApiResponse l = coinExchangeMoneyConvernet(authUser);
        if (l.isState() == false) {
            return l;
        }
        Object data1 = l.getData();
        Map data = (Map) data1;
        BigDecimal moneyBd = new BigDecimal(money);

        if (BigDecimalUtils.lessThan(moneyBd, (new BigDecimal("0.5")))) {
            return new ApiResponse("最小兑换0.5");
        }
        MemberBillSpeedIntegral memberBillSpeedIntegral = MemberBillSpeedIntegral.dao.getMemberBillSpeedIntegralByUserId(authUser);
        if (memberBillSpeedIntegral == null) {
            return new ApiResponse(false, "可兑换金额为0");
        }
        BigDecimal coin = memberBillSpeedIntegral.getCoin() == null ? BigDecimal.ZERO : memberBillSpeedIntegral.getCoin();
        if (BigDecimalUtils.greaterThan(moneyBd, coin)) {
            return new ApiResponse(false, "提现的金额过大,请重试");
        }
//      佣金兑换现金比例
        MemberLevel memberLevel = MemberLevel.dao.getMemberLevel(MemberInfoEnum.THIRD_LEVEL.getCode());
        double coinExchangeBalancePercent = MemberLevel.coinExchangeBalancePercent(memberLevel);
//      手续费coinExchangeMoneyProportion
        BigDecimal subBd = BigDecimal.valueOf(coinExchangeBalancePercent);
        BigDecimal commission = moneyBd.multiply(subBd);

        MemberCommisionLog memberCommisionLog = new MemberCommisionLog();
        memberCommisionLog.setMemberCommisionLogByUserId(authUser, openid, moneyBd, commission, 1,
                new Date().getTime(), "佣金提现", 1);
        memberCommisionLog.save();
        return new ApiResponse(true, "等待审核...");
    }

    //        BigDecimal moneySum = moneyBd.subtract(commission);
//        BigDecimal othermoneyBd = moneySum.multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP);
//        String i = othermoneyBd.toString();
    /**
     * 积分兑换现金
     */
    public ApiResponse exchange(String id) {

        MemberCommisionLog commission = MemberCommisionLog.dao.getMemberComissionLog(id);
        if(commission==null){
            return new ApiResponse(false, "没有找到该订单");
        }
        String openid = commission.getOpenid();
        String userId = commission.getUserId();
        BigDecimal balance = commission.getBalance();
        BigDecimal commissionBd = commission.getCommission();

        if (StringUtils.isBlank(openid)) {
            return new ApiResponse(false, "微信授权openid不存在");
        }
        if (StringUtils.isBlank(userId)) {
            return new ApiResponse(false, "没有找到该用户");
        }
        BigDecimal moneySum = balance.subtract(commission.getCommission());
        BigDecimal othermoneyBd = moneySum.multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP);
        String othermoneyStr = othermoneyBd.toString();

        String pathKit = PathKit.getRootClassPath() + "/weixin/cer/zhongke_apiclient_cert.p12";
        CompanyToPerson companyToPerson = new CompanyToPerson();
        WeixinTransferResult transfer = companyToPerson.transfer("wx001ef33c1c1512d9", "1561327181",
                pathKit, openid, System.currentTimeMillis() / 1000 + "",
                othermoneyStr, "金币兑换现金");

        boolean state = transfer.isState();
        if (!state) {
            commission.setStatus(3);
            commission.update();
            return new ApiResponse(true, "兑换失败", transfer.getReturn_msg());
        }

        commission.setStatus(2);
        commission.setRevenueTime(new Date().getTime());
        commission.update();

        CompanyCoin companyCoin = new CompanyCoin();
        companyCoin.setCompanyCoin(userId, commissionBd);
        companyCoin.save();

        List<Company> companyList = Company.dao.findAll();
        Optional<Company> first = companyList.stream().filter(company -> new Integer("1").equals(company.getType())).findFirst();
        if (first.isPresent()) {
            Company company = first.get();
            BigDecimal count = company.getCount();
            BigDecimal add = count.add(commissionBd);
            company.setCount(add);
            company.setUpdateTime(new Date().getTime());
            company.update();
        } else {
            Company company = new Company();
            company.setId(UUIDUtils.getUUIDInOrderId() + "");
            company.setType(1);
            company.setCount(commissionBd);
            Long date = new Date().getTime();
            company.setCreateTime(date);
            company.setUpdateTime(date);
            company.save();
        }

        MemberBillSpeedIntegral memberBillSpeedIntegral = MemberBillSpeedIntegral.dao.getMemberBillSpeedIntegralByUserId(userId);
        BigDecimal coin = memberBillSpeedIntegral.getCoin();
        BigDecimal remainCoinBd = coin.subtract(balance);
        memberBillSpeedIntegral.setCoin(remainCoinBd);
        memberBillSpeedIntegral.setUpdateTime(new Date().getTime());
        memberBillSpeedIntegral.update();
        return new ApiResponse(true, "兑换成功");

    }

    /**
     * 提现记录
     *
     * @param id
     * @return
     */
    public List<MemberCommisionLog> getCommision(String id) {
        List<MemberCommisionLog> commision = MemberCommisionLog.dao.getCommision(id);
        return commision;
    }
}
